package com.lalilu.homework8.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.lalilu.homework8.R;
import com.lalilu.homework8.utils.SHA256Utils;

public class Fragment_3 extends Fragment {

    private static final String SHARED_PREFERENCES_FILE = "SHARED_PREFERENCES_FILE_DATA";

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        EditText username = view.findViewById(R.id.username);
        EditText password = view.findViewById(R.id.password);
        Button register = view.findViewById(R.id.register);
        Button login = view.findViewById(R.id.login);

        register.setOnClickListener(v -> {
            SharedPreferences sharedPreferences = requireActivity().getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
            String passwordText = sharedPreferences.getString(username.getText().toString(), "null");
            if (passwordText.equals("null")) {
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString(username.getText().toString(), SHA256Utils.getSHA256(password.getText().toString()));
                editor.apply();
                editor.commit();

                Toast.makeText(requireActivity(), username.getText().toString() + " 注册成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(requireActivity(), username.getText().toString() + " 已存在", Toast.LENGTH_SHORT).show();
            }
        });

        login.setOnClickListener(v -> {
            SharedPreferences sharedPreferences = requireActivity().getSharedPreferences(SHARED_PREFERENCES_FILE, Context.MODE_PRIVATE);
            String passwordText = sharedPreferences.getString(username.getText().toString(), "null");

            if (passwordText.equals(SHA256Utils.getSHA256(password.getText().toString()))) {
                Toast.makeText(requireActivity(), "登录成功", Toast.LENGTH_SHORT).show();
                password.setText(passwordText);
            } else if (passwordText.equals("null")) {
                Toast.makeText(requireActivity(), "用户名不存在", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(requireActivity(), "密码错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_2, container, false);
    }
}